/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) return null;
        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
    private TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
        if (preStart > preEnd || inStart > inEnd || preStart >= preorder.length || inStart >= inorder.length) {
            return null;
        }
        TreeNode node = new TreeNode(preorder[preStart]);
        for (int i = inStart; i <= inEnd; i++) {
            if (node.val == inorder[i]) {
                int leftTreeSize = i - inStart;
                node.left = buildTree(preorder, preStart + 1, preStart + leftTreeSize, inorder, inStart, i);
                node.right = buildTree(preorder, preStart + 1 + leftTreeSize, preEnd, inorder, i + 1, inEnd);
                break;
            }
        }
        return node;
    }
}
